package com.liuweiheng.cloudproviderpayment8002.shiro.realm;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.liuweiheng.cloudproviderpayment8002.common.service.UserService;
import com.liuweiheng.cloudproviderpayment8002.entity.Permission;
import com.liuweiheng.cloudproviderpayment8002.entity.Role;
import com.liuweiheng.cloudproviderpayment8002.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Realm：基础Realm
 *
 * @author lwh
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 获取用户身份信息
        String primaryPrincipal = String.valueOf(principals.getPrimaryPrincipal());

        // 获取用户角色
        List<Role> roles = userService.selectRoleByUsername(primaryPrincipal);

        // 添加角色
        if (CollectionUtil.isNotEmpty(roles)) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

            List<Integer> roleIds = new ArrayList<>(10);

            roles.forEach(role -> {
                roleIds.add(role.getId());
                info.addRole(role.getName());
            });

            // 查询所有角色对应的权限
            List<Permission> permissions = userService.selectPermByRoleIds(roleIds);

            // 添加权限
            permissions.forEach(perm -> info.addStringPermission(perm.getName()));

            return info;
        }

        return null;
    }


    /**
     * 认证
     * @param token 身份凭证信息
     * @return 认证信息
     * @throws AuthenticationException 认证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String principal = String.valueOf(token.getPrincipal());

        User user = userService.selectUserByUsername(principal);

        if (ObjectUtil.isNull(user)) {
            return null;
        }

        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), new MyByteSource(user.getSalt()), this.getName());

    }
}
